Page({
  data: {
    // 用户登录状态
    isLogin: false,
    userPhone: '',

    // 社区动态数据
    posts: [],

    // 加载状态
    loading: true,
    loadingMore: false,
    error: '',
    hasMore: true,

    // 分页参数
    page: 1,
    pageSize: 20,

    // 热门话题
    hotTopics: [
      { id: 1, name: '#今日大盘#', count: '2.3万' },
      { id: 2, name: '#新能源车#', count: '1.8万' },
      { id: 3, name: '#人工智能#', count: '1.5万' },
      { id: 4, name: '#银行股#', count: '1.2万' },
      { id: 5, name: '#医药股#', count: '0.9万' },
      { id: 6, name: '#房地产#', count: '0.7万' }
    ],

    // 当前数据源
    currentSource: 'xueqiu'
  },

  onLoad: function (options) {
    // 检查登录状态
    this.checkLoginStatus();

    // 设置页面标题
    wx.setNavigationBarTitle({
      title: '投资社区'
    });

    // 加载社区数据
    this.loadCommunityData();
  },

  onShow: function () {
    // 每次显示页面时刷新登录状态
    this.checkLoginStatus();
  },

  // 检查登录状态
  checkLoginStatus: function () {
    const app = getApp();
    this.setData({
      isLogin: app.globalData.isLogin || false,
      userPhone: app.globalData.userPhone || ''
    });
  },

  // 加载社区数据
  loadCommunityData: function () {
    this.setData({
      loading: true,
      error: '',
      page: 1,
      posts: []
    });

    // 根据当前数据源加载数据
    switch (this.data.currentSource) {
      case 'xueqiu':
        this.loadXueqiuData();
        break;
      case 'eastmoney':
        this.loadEastmoneyData();
        break;
      case 'sina':
        this.loadSinaData();
        break;
      default:
        this.loadBackupData();
    }
  },

  // 雪球数据加载
  loadXueqiuData: function () {
    const that = this;

    // 由于雪球API需要认证，这里使用模拟数据
    const xueqiuPosts = [
      {
        id: 1,
        avatar: '/images/xueqiu-avatar.png',
        username: '雪球用户_投资达人',
        time: '30分钟前',
        title: '今日A股三大指数集体收涨，科技股表现亮眼',
        summary: '沪指涨0.8%，深成指涨1.2%，创业板指涨1.5%，两市成交额超8000亿元',
        source: '雪球',
        stocks: ['000001', '399001', '399006'],
        topics: ['大盘分析', '科技股'],
        likes: 156,
        comments: 42,
        views: 1280
      },
      {
        id: 2,
        avatar: '/images/xueqiu-avatar.png',
        username: '价值投资者老王',
        time: '1小时前',
        title: '新能源汽车板块持续走强，产业链公司受益明显',
        summary: '比亚迪、宁德时代等龙头股创新高，新能源车销量数据超预期',
        source: '雪球',
        stocks: ['002594', '300750'],
        topics: ['新能源车', '产业链'],
        likes: 203,
        comments: 67,
        views: 2150
      },
      {
        id: 3,
        avatar: '/images/xueqiu-avatar.png',
        username: '量化分析师小李',
        time: '2小时前',
        title: 'AI概念股再度活跃，ChatGPT热度不减',
        summary: '人工智能板块涨幅居前，多只AI概念股涨停，市场关注度持续提升',
        source: '雪球',
        stocks: ['002230', '300496'],
        topics: ['人工智能', 'ChatGPT'],
        likes: 189,
        comments: 55,
        views: 1890
      }
    ];

    setTimeout(() => {
      that.setData({
        posts: xueqiuPosts,
        loading: false,
        hasMore: true
      });
    }, 1000);
  },

  // 东方财富数据加载
  loadEastmoneyData: function () {
    const that = this;

    // 使用东方财富股吧相关的模拟数据
    const eastmoneyPosts = [
      {
        id: 1,
        avatar: '/images/eastmoney-avatar.png',
        username: '东财股友_价值发现',
        time: '45分钟前',
        title: '银行股估值修复行情启动，关注优质标的',
        summary: '四大行股价创年内新高，银行板块估值仍处历史低位，具备配置价值',
        source: '东方财富',
        stocks: ['601398', '000001', '601288'],
        topics: ['银行股', '估值修复'],
        likes: 134,
        comments: 38,
        views: 1120
      },
      {
        id: 2,
        avatar: '/images/eastmoney-avatar.png',
        username: '股市老司机',
        time: '1小时前',
        title: '医药板块迎来政策利好，创新药企业受关注',
        summary: '国家医保局发布新政策，支持创新药发展，相关企业有望受益',
        source: '东方财富',
        stocks: ['000661', '300015'],
        topics: ['医药股', '政策利好'],
        likes: 167,
        comments: 51,
        views: 1450
      },
      {
        id: 3,
        avatar: '/images/eastmoney-avatar.png',
        username: '技术分析师',
        time: '2小时前',
        title: '消费板块估值回归合理区间，白酒龙头值得关注',
        summary: '随着消费复苏预期升温，白酒、食品等消费股重新获得市场青睐',
        source: '东方财富',
        stocks: ['000858', '000568'],
        topics: ['消费股', '白酒'],
        likes: 198,
        comments: 73,
        views: 1890
      }
    ];

    setTimeout(() => {
      that.setData({
        posts: eastmoneyPosts,
        loading: false,
        hasMore: true
      });
    }, 1200);
  },

  // 新浪财经数据加载
  loadSinaData: function () {
    const that = this;

    const sinaPosts = [
      {
        id: 1,
        avatar: '/images/sina-avatar.png',
        username: '新浪财经_市场观察',
        time: '20分钟前',
        title: '北向资金连续净流入，外资看好A股长期价值',
        summary: '本周北向资金累计净流入超100亿元，主要流入消费、科技等板块',
        source: '新浪财经',
        stocks: ['000858', '000002'],
        topics: ['北向资金', '外资'],
        likes: 145,
        comments: 29,
        views: 980
      },
      {
        id: 2,
        avatar: '/images/sina-avatar.png',
        username: '财经评论员',
        time: '1小时前',
        title: '房地产政策边际改善，地产股迎来反弹机会',
        summary: '多地优化房地产调控政策，市场预期逐步改善，地产股表现活跃',
        source: '新浪财经',
        stocks: ['000002', '001979'],
        topics: ['房地产', '政策'],
        likes: 112,
        comments: 45,
        views: 1230
      }
    ];

    setTimeout(() => {
      that.setData({
        posts: sinaPosts,
        loading: false,
        hasMore: true
      });
    }, 800);
  },

  // 切换数据源
  switchSource: function (e) {
    const source = e.currentTarget.dataset.source;
    if (source === this.data.currentSource) return;

    this.setData({
      currentSource: source,
      posts: [],
      page: 1,
      hasMore: true
    });

    this.loadCommunityData();
  },

  // 刷新数据
  refreshData: function () {
    this.setData({
      page: 1,
      posts: [],
      hasMore: true
    });
    this.loadCommunityData();
  },

  // 重试加载
  retryLoad: function () {
    this.loadCommunityData();
  },

  // 加载更多
  loadMore: function () {
    if (this.data.loadingMore || !this.data.hasMore) return;

    this.setData({
      loadingMore: true,
      page: this.data.page + 1
    });

    // 模拟加载更多数据
    setTimeout(() => {
      const morePosts = this.generateMorePosts();
      this.setData({
        posts: [...this.data.posts, ...morePosts],
        loadingMore: false,
        hasMore: morePosts.length === this.data.pageSize
      });
    }, 1000);
  },

  // 生成更多帖子数据
  generateMorePosts: function () {
    const currentLength = this.data.posts.length;
    const morePosts = [];

    for (let i = 0; i < 5; i++) {
      morePosts.push({
        id: currentLength + i + 1,
        avatar: '/images/default-avatar.png',
        username: `投资者${currentLength + i + 1}`,
        time: `${i + 3}小时前`,
        title: `投资观点分享 - 第${currentLength + i + 1}条`,
        summary: '分享一些个人的投资心得和市场观察...',
        source: this.data.currentSource === 'xueqiu' ? '雪球' :
          this.data.currentSource === 'eastmoney' ? '东方财富' : '新浪财经',
        stocks: ['000001', '399001'],
        topics: ['投资心得'],
        likes: Math.floor(Math.random() * 100) + 20,
        comments: Math.floor(Math.random() * 30) + 5,
        views: Math.floor(Math.random() * 500) + 100
      });
    }

    return morePosts;
  },



  // 加载备用数据
  loadBackupData: function () {
    console.log('使用备用社区数据');

    const backupPosts = [
      {
        id: 1,
        avatar: '/images/default-avatar.png',
        username: '投资达人',
        time: '刚刚',
        title: 'A股三大指数震荡上行，沪指站稳3200点',
        summary: '市场成交量温和放大，投资者情绪逐步回暖，权重股表现稳健',
        source: '社区',
        stocks: ['000001', '399001'],
        topics: ['大盘', '指数'],
        likes: 168,
        comments: 32,
        views: 1250
      },
      {
        id: 2,
        avatar: '/images/default-avatar.png',
        username: '价值投资者',
        time: '30分钟前',
        title: '北向资金连续5日净流入，累计买入超100亿元',
        summary: '外资持续看好A股投资价值，重点配置消费和科技龙头股',
        source: '社区',
        stocks: ['000858', '000002'],
        topics: ['北向资金', '外资'],
        likes: 142,
        comments: 28,
        views: 980
      },
      {
        id: 3,
        avatar: '/images/default-avatar.png',
        username: '成长股猎手',
        time: '1小时前',
        title: '新能源车销量再创新高，产业链公司订单饱满',
        summary: '11月新能源汽车销量同比增长超30%，行业景气度持续提升',
        source: '社区',
        stocks: ['002594', '300750'],
        topics: ['新能源', '汽车'],
        likes: 195,
        comments: 41,
        views: 1560
      }
    ];

    this.setData({
      posts: backupPosts,
      loading: false,
      hasMore: true
    });
  },

  // 点击话题
  clickTopic: function (e) {
    const topic = e.currentTarget.dataset.topic;
    wx.showToast({
      title: `查看话题: ${topic.name}`,
      icon: 'none'
    });
  },

  // 点击帖子
  clickPost: function (e) {
    const post = e.currentTarget.dataset.post;

    // 显示帖子详情或跳转到详情页
    wx.showModal({
      title: post.title,
      content: post.summary,
      showCancel: false,
      confirmText: '知道了'
    });
  },

  // 点击股票标签
  clickStock: function (e) {
    const stock = e.currentTarget.dataset.stock;

    // 跳转到股票详情页
    wx.navigateTo({
      url: `/pages/stock/index?code=${stock}`
    });
  },

  // 下拉刷新
  onPullDownRefresh: function () {
    this.refreshData();

    setTimeout(() => {
      wx.stopPullDownRefresh();
      wx.showToast({
        title: '刷新成功',
        icon: 'success'
      });
    }, 1000);
  },

  // 上拉加载更多
  onReachBottom: function () {
    this.loadMore();
  }
});